package com.ScoresSystem.advice;

import com.ScoresSystem.utils.Result;
import com.google.gson.Gson;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Aspect
@Component // 表示该类是一个切面类
public class LonginAdvice {

    @Autowired
    HttpSession session;

    @Autowired
    HttpServletResponse response;

    // 环绕切点
    @Around("execution(* com.ScoresSystem.controller.*.*(..))")
    public Object around(ProceedingJoinPoint pjp) {
        try {
            String MethodName = pjp.getSignature().getName();
            if("createCode".equals(MethodName) || "login".equals(MethodName)){
                return pjp.proceed();
            }
            Object obj = session.getAttribute("nowusername");
            if(obj == null){
                Result<String> result = new Result<>("403", "没有权限访问,请先登录");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(new Gson().toJson(result));
                return null;
            }
            return pjp.proceed();
        } catch (Throwable e) {
            try {
                Result<String> result = new Result<>("500", "服务器开小差了");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(new Gson().toJson(result));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } finally {
            // 一般用于记录用户访问信息和操作日志
        }
        return null;
    }
}
